<template>
  <button @click="openDialog">提交砍价</button>
  <el-dialog
    v-model="dialogVisible"
    title="填写砍价意向"
    width="50%"
    :before-close="handleClose"
  >
    <el-form :model="form" label-width="120px">
      <el-form-item label="商品名称">
        <el-input v-model="name" disabled />
      </el-form-item>
      
      <el-form-item label="商品原价">
        <el-input v-model="Price" disabled>
          <template #append>元</template>
        </el-input>
      </el-form-item>
      
      <el-form-item label="砍价金额" prop="bargainPrice" required>
          <el-input v-model="vprice" placeholder="请输入砍价金额">
          <template #append>元</template>
        </el-input>
      </el-form-item>
      
      <el-form-item label="备注">
        <el-input
          v-model="form.remark"
          type="textarea"
          :rows="2"
          placeholder="请输入您的砍价理由"
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitBargain">提交砍价</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { onMounted,ref, computed } from 'vue'
import { ElMessage } from 'element-plus'


onMounted(() => {
  // 获取设备信息数据
  // getDeviceData();
 // 主组件逻辑完成后，允许子组件渲染
dialogVisible.value = true
})

const props = defineProps({
  equipmentId: {
    type: Number,
    required: true
  },
  equipmentName: {
    type: String,
    default: ''
  },
  originalPrice: {
    type: Number,
    default: 0
  }
})

const emit = defineEmits(['submit-success'])

const dialogVisible = ref(false)
const form = ref({
  bargainPrice: 0,
  remark: ''
})

// 计算最小砍价金额（原价的80%）
const minBargainPrice = computed(() => {
  return Math.round(props.originalPrice * 0.8 * 100) / 100
})

// 计算最大砍价金额（原价的95%）
const maxBargainPrice = computed(() => {
  return Math.round(props.originalPrice * 0.95 * 100) / 100
})

// 初始化默认砍价金额（取中间值）
const initDefaultPrice = () => {
  form.value.bargainPrice = Math.round((minBargainPrice.value + maxBargainPrice.value) / 2 * 100) / 100
}

const openDialog = () => {
  initDefaultPrice()
  dialogVisible.value = true
}

const handleClose = (done) => {
  ElMessageBox.confirm('确定要关闭吗？未提交的砍价信息将丢失')
    .then(() => done())
    .catch(() => {})
}

const submitBargain = async () => {
  if (form.value.bargainPrice <= 0) {
    ElMessage.error('请输入有效的砍价金额')
    return
  }
  
  try {
    // 调用API提交砍价
    const res = await apiSubmitBargain({
      equipmentId: props.equipmentId,
      bargainPrice: form.value.bargainPrice,
      remark: form.value.remark
    })
    
    ElMessage.success('砍价申请已提交')
    dialogVisible.value = false
    emit('submit-success', res.data)
  } catch (error) {
    ElMessage.error(error.message || '提交失败')
  }
}

defineExpose({
  openDialog
})
</script>

<style scoped>
.tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}
</style>